package com.codeforjava.blog.controller.admin;

import com.codeforjava.blog.dao.UserDao;
import com.codeforjava.blog.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @Author: dinian 2018/1/23
 */
@RestController
public class UserController {

    @Autowired
    private UserDao userDao;

    /**
     * 查下用户列表
     * @return
     */
    @GetMapping("/users")
    public List<User> getUsers(){
        return userDao.findAll();
    }

    /**
     * 查询一个用户
     * @param id
     * @return
     */
    @GetMapping("/user/{id}")
    public User getUsers(@PathVariable("id") Integer id){
        return userDao.findOne(id);
    }

    /**
     * 添加用户
     * @param username
     * @param Password
     * @return
     */
    @PostMapping("/user")
    public User addUser(@RequestParam("username") String username,
                        @RequestParam("password") String Password){

        User user = new User();
        user.setName(username);
        user.setPassword(Password);
        return userDao.save(user);
    }

    /**
     * 更新用户
     * @param username
     * @param password
     * @param id
     * @return
     */
    @PutMapping("/user/{id}")
    public User updateUser(@RequestParam(value = "username",required = false,defaultValue = "default") String username,
                           @RequestParam("password") String password,
                           @PathVariable("id") Integer id){
        User user = new User();
        user.setId(id);
        user.setName(username);
        user.setPassword(password);
        return userDao.save(user);
    }

    /**
     * 删除一条用户
     * @param id
     * @return
     */
    @DeleteMapping("/user/{id}")
    public int deleteUser(@PathVariable("id") Integer id){
        userDao.delete(id);
        return 1;
    }
}
